#include "dashboardwidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QStringList>
#include <QQuickWidget>
#include <QQmlContext>
#include <QDir>
#include <QResizeEvent>

DashboardWidget::DashboardWidget(QWidget *parent)
    : QWidget(parent)
{
    // 主布局为垂直布局
    mainLayout = new QVBoxLayout(this);
    QStringList params = {"温度(℃)", "湿度(%)", "光照强度(lx)", "土壤墒情(%)"};
    for (const QString &param : params) {
        QLabel *label = new QLabel(param + ": --", this);
        label->setStyleSheet("font-size: 18px;");
        mainLayout->addWidget(label);
        paramLabels[param] = label;
    }
    // 仪表盘容器
    contentLayout = new QHBoxLayout();
    // QML仪表盘
    gaugeQmlWidget = new QQuickWidget(this);
    gaugeQmlWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
    gaugeQmlWidget->setSource(QUrl::fromLocalFile(QDir::currentPath() + "/qml/DashboardGauge.qml"));
    gaugeQmlWidget->rootContext()->setContextProperty("gaugeValue", 0.0);
    gaugeQmlWidget->rootContext()->setContextProperty("gaugeLabel", QString("温度(℃)"));
    gaugeQmlWidget->setMinimumHeight(220);
    gaugeQmlWidget->setMinimumWidth(220);
    contentLayout->addWidget(gaugeQmlWidget, 1);
    mainLayout->addLayout(contentLayout);
    mainLayout->addStretch();
}

void DashboardWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    // 响应式布局：宽度大于高度时左右排列，否则上下排列
    if (width() > height()) {
        if (mainLayout->indexOf(contentLayout) == -1) {
            mainLayout->insertLayout(1, contentLayout);
        }
        contentLayout->setDirection(QBoxLayout::LeftToRight);
    } else {
        if (mainLayout->indexOf(contentLayout) == -1) {
            mainLayout->insertLayout(mainLayout->count() - 1, contentLayout);
        }
        contentLayout->setDirection(QBoxLayout::TopToBottom);
    }
}

void DashboardWidget::setParameter(const QString &name, double value)
{
    if (paramLabels.contains(name)) {
        paramLabels[name]->setText(QString("%1: %2").arg(name).arg(value, 0, 'f', 2));
    }
    // 只同步温度到QML仪表盘
    if (name == "温度(℃)" && gaugeQmlWidget) {
        gaugeQmlWidget->rootContext()->setContextProperty("gaugeValue", value);
    }
}

void DashboardWidget::setParameterHighlight(const QString &name, bool highlight)
{
    if (paramLabels.contains(name)) {
        if (highlight) {
            paramLabels[name]->setStyleSheet("font-size: 18px; color: red; font-weight: bold;");
        } else {
            paramLabels[name]->setStyleSheet("font-size: 18px; color: black;");
        }
    }
} 